#ifndef __SINGLETON_H___
#define __SINGLETON_H___
#include <pthread.h>
#include <new>
#include <assert.h>
template <typename T>
class Singleton
{
    public:
        static T* Instance();

    protected:
        virtual ~Singleton();
        inline explicit Singleton();

    private:
        static T* _instance;
		static pthread_mutex_t m_mutex;
};

template<typename T>
T* Singleton<T>::_instance = NULL;

template<typename T>
pthread_mutex_t Singleton<T>::m_mutex = PTHREAD_MUTEX_INITIALIZER;

template <typename T>
Singleton<T>::Singleton()
{
    assert(Singleton::_instance == NULL);
	pthread_mutex_init(&m_mutex, NULL);
}

template<typename T>
T* Singleton<T>::Instance()
{
	if (Singleton::_instance == NULL)
    { 
		pthread_mutex_lock(&m_mutex);
		if (Singleton::_instance == NULL)
		{
			Singleton::_instance = new (std::nothrow)T();
			assert(Singleton::_instance != NULL);
		}
		pthread_mutex_unlock(&m_mutex);
    }
    return Singleton::_instance;
}


template<typename T>
Singleton<T>::~Singleton()
{
    if(Singleton::_instance != NULL)
    {
        delete Singleton::_instance;
    }
	pthread_mutex_destroy(&m_mutex);
	Singleton::_instance = NULL;
}

#endif // SINGLETON_H
